export function formTemplate(json, options) {
  return `<template>
  <form-create
    v-model="formData"
    v-model:api="fapi"
    :rule="rule"
    :option="option"
    @submit="onSubmit"
  ></form-create>
</template>

<script>
import formCreate from "@form-create/element-ui";

export default {
  components: {
    formCreate: formCreate.$form()
  },
  data () {
    const option = formCreate.parseJson('${options.replaceAll('\\', '\\\\').replaceAll("'", "\\'")}');
    return {
      formData: {},
      fapi: null,
      rule: formCreate.parseJson('${json.replaceAll('\\', '\\\\').replaceAll("'", "\\'")}'),
      option: option
    }
  },
  methods: {
    onSubmit (formData) {
      //todo 提交表单
    }
  }
}
</script>`
}

export function ruleTemplate(value) {
  const customValuesArray = [] // 存储所有 custom_value 的数组
  function formatRuleItem(ruleItem) {
    console.log('ruleItem', ruleItem)
    const formatted = { ...ruleItem } // 从原始项开始创建副本

    // 如果 defaultData 中存在对应的 field，默认值将被添加
    if (value.defaultData && value.defaultData[formatted.field] !== undefined) {
      formatted.value = value.defaultData[formatted.field]
    }

    // 移除具有默认值或内部使用的属性
    if (!formatted.$required) delete formatted.$required
    if (formatted.display) delete formatted.display
    if (!formatted.hidden) delete formatted.hidden
    delete formatted._fc_id
    delete formatted.name
    delete formatted._fc_drag_tag

    // 只保留必要的字段
    const essentialFields = ['type', 'field', 'title', 'info', '$help', 'value', 'props', 'options', 'control']
    const cleanFormatted = {}
    essentialFields.forEach((key) => {
      if (formatted[key] !== undefined) {
        cleanFormatted[key] = formatted[key]
      }
    })

    // 特殊处理 controlType 和 _controls
    if (formatted.controlType === 'input') {
      // TODO  这里要修改一下，程序会自动给我格式化
      console.log('control', formatted.control)
      cleanFormatted.controlType = undefined
      cleanFormatted._controls = undefined
    } else if (formatted.controlType === 'select') {
      // 删除 controlType 后处理 _controls
      cleanFormatted.controlType = undefined
      // 循环处理_controls
      if (formatted._controls) {
        cleanFormatted.control = formatted._controls
          .map((control) => {
            if (control.valueType === 'eq') {
              return {
                value: control.value,
                rule: control.rules.rule?.map(formatRuleItem)
              }
            } else if (control.valueType === 'input') {
              const customValueIndex = customValuesArray.indexOf(control.custom_value)
              let key
              if (customValueIndex === -1) {
                key = customValuesArray.length // 新的索引
                customValuesArray.push(control.custom_value) // 存入数组
              } else {
                key = customValueIndex // 如果已存在，则使用已有的索引
              }
              return {
                value: 'custom_' + key,
                rule: control.rules.rule?.map(formatRuleItem)
              }
            }
            return null // 添加默认返回值
          })
          .filter(Boolean)
      }
      cleanFormatted._controls = undefined
    }

    return cleanFormatted
  }

  // 确保 style 和 setting 存在，如果不存在则初始化为空对象
  const preferenceData = {
    ...value.preferenceData,
    style: value.preferenceData.style || {},
    setting: value.preferenceData.setting || {}
  }
  console.log('value.defaultData', value.defaultData)
  // 生成模板字符串
  return `const label = '${preferenceData.label}';
const name = '${preferenceData.name}';

export default {
  icon: '${preferenceData.icon}',
  label,
  name,
  count: ${preferenceData.count},
  fixed: ${preferenceData.fixed},
  rule() {
    return {
      type: name,
      props: {
        ${(() => {
          // 获取当前rule中所有的field
          const currentFields = new Set(value.rule?.map((item) => item.field) || [])

          return Object.entries(value.defaultData || {})
            .filter(([key, val]) => {
              // 只包含当前rule中存在的字段，并且值不为空
              return currentFields.has(key) && val !== undefined && val !== null && val !== ''
            })
            .map(([key, val]) => `${key}: '${val}'`)
            .join(',\n        ')
        })()}
      },
      showStyle: true,
      children: [],
      style: ${JSON.stringify(preferenceData.style)},
      setting: ${JSON.stringify(preferenceData.setting)}
    };
  },
  props() {
    return [
      ${value.rule
        .map(formatRuleItem)
        .map((item) => {
          console.log('item', item)
          let str = JSON.stringify(item)
          // 这里要处理custom_value
          str = str.replace(/"value":"custom_(\d+)"/g, (match, key) => {
            const originalValue = customValuesArray[key] // 获取原始的 custom_value
            return `${originalValue}` // 替换为原始的 custom_value
          })

          return str
        })
        .join(',\n      ')}
    ];
  }
}
`
}
// 后台管理的组件模板
export function adminComponentTemplate(value) {
  // 辅助函数用于格式化 props 内部的对象
  function formatRuleItem(ruleItem) {
    const formatted = { ...ruleItem } // 从原始项开始创建副本

    // 如果 defaultData 中存在对应的 field，默认值将被添加
    if (value.defaultData[formatted.field] !== undefined) {
      formatted.value = value.defaultData[formatted.field]
    }

    // 移除具有默认值或内部使用的属性
    if (!formatted.$required) delete formatted.$required
    if (formatted.display) delete formatted.display
    if (!formatted.hidden) delete formatted.hidden
    delete formatted._fc_id
    delete formatted.name
    delete formatted._fc_drag_tag

    return formatted
  }
  function capitalizeFirstLetter(str) {
    if (typeof str !== 'string' || str.length === 0) {
      return str
    }
    return str.charAt(0).toUpperCase() + str.slice(1)
  }
  // 动态生成 props 的内容
  function generatePropsContent(rules) {
    return rules
      .map(formatRuleItem)
      .map((item) => {
        let defaultValue = item.value
        let type = capitalizeFirstLetter(typeof defaultValue)
        if (typeof defaultValue === 'object' && Array.isArray(defaultValue)) {
          type = 'Array'
        } else if (typeof defaultValue === 'object' && !Array.isArray(defaultValue)) {
          type = 'Object'
        }
        switch (type) {
          case 'String':
            defaultValue = "'" + String(defaultValue) + "'"
            break
          case 'Number':
            defaultValue = Number(defaultValue)
            break
          case 'Boolean':
            defaultValue = Boolean(defaultValue)
            break
          case 'Array':
            defaultValue = `()=>{
              return ${JSON.stringify(defaultValue)}
            }`
            break
          case 'Object':
            defaultValue = `()=>{
              return ${JSON.stringify(defaultValue)}
            }`
            break
        }

        if (type === 'Array' || type === 'Object') {
          return `        ${item.field}: {
          type: ${type},
          default: ${defaultValue}
        }`
        } else {
          return `        ${item.field}: { type: ${type}, default: ${defaultValue} }`
        }
      })
      .join(',\n')
  }

  // 确保 style 和 setting 存在，如果不存在则初始化为空对象
  const preferenceData = {
    ...value.preferenceData,
    style: value.preferenceData.style || {},
    setting: value.preferenceData.setting || {}
  }

  // 动态生成 props
  const propsContent = generatePropsContent(value.rule)

  // 生成模板字符串
  return `<template>
  <div></div>
</template>

<script>
export default {
  name: '${preferenceData.name}',
  props: {
${propsContent}
  },
  data() {
    return {
    }
  },
  computed: {},
  watch: {},
  mounted() {
  }
}
</script>

<style scoped lang="scss">
/* 样式可以根据需要添加 */
</style>
`
}

// 测试函数输出
export function formTemplateV3(json, options) {
  return `<template>
  <form-create
    v-model="formData"
    v-model:api="fapi"
    :rule="rule"
    :option="option"
    @submit="onSubmit"
  ></form-create>
</template>

<script setup>
import {ref} from "vue";
import formCreate from "@form-create/element-ui";

const option = ref(formCreate.parseJson('${options.replaceAll('\\', '\\\\').replaceAll("'", "\\'")}'));
const rule = ref(formCreate.parseJson('${json.replaceAll('\\', '\\\\').replaceAll("'", "\\'")}'));
const fapi = ref(null);
const formData = ref({});

const onSubmit =  (formData) => {
  //todo 提交表单
}
</script>`
}

export function htmlTemplate(json, options) {
  return `<html lang="zh">
    <head>
        <meta charset="UTF-8">
        <!-- Import style -->
        <link rel="stylesheet" href="//unpkg.com/element-plus/dist/index.css"/>
        <!-- Import Vue 3 -->
        <script src="//unpkg.com/vue@3"></script>
        <!-- Import element-plus -->
        <script src="//unpkg.com/element-plus"></script>
        <!-- Import formCreate -->
        <script src="//unpkg.com/@form-create/element-ui@3"></script>
    </head>
    <body>
        <div id="app">
            <form-create :rule="rule" :option="options" v-model="formData" v-model:api="api" @submit="onSubmit"></form-create>
        </div>
        <script>
            const App = {
                data() {
                    return {
                        rule: formCreate.parseJson('${json.replaceAll('\\', '\\\\').replaceAll("'", "\\'")}'),
                        options: formCreate.parseJson('${options.replaceAll('\\', '\\\\').replaceAll("'", "\\'")}'),
                        formData: {},
                        api: null,
                    };
                },
                methods: {
                    onSubmit(formData){
                        console.log('submit', formData);
                    }
                }
            };
            const app = Vue.createApp(App);
            app.use(ElementPlus).use(formCreate);
            app.mount("#app");
        </script>
    </body>
</html>`
}
